import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/providers/session_provider.dart';
import 'package:merchants/providers/dio_provider.dart';

class AgreementManager {
  static const MethodChannel _channel = MethodChannel(
    'com.shopthrive.merchants/agreement',
  );

  // 本地存储键名（统一使用这个）
  static const String _agreementKey = 'agreed_to_terms';
  static const String _agreementVersionKey = 'agreement_version';
  static const String _agreementDateKey = 'agreement_date';
  
  // 当前协议版本
  static const String _currentVersion = '1.0.0';

  // 检查是否已同意协议（本地检查）
  static Future<bool> hasAgreed() async {
    final prefs = await SharedPreferences.getInstance();
    final agreed = prefs.getBool(_agreementKey) ?? false;
    final version = prefs.getString(_agreementVersionKey);
    
    // 如果版本不匹配，需要重新同意
    if (agreed && version != _currentVersion) {
      return false;
    }
    
    return agreed;
  }

  // 获取同意时间
  static Future<DateTime?> getAgreementDate() async {
    final prefs = await SharedPreferences.getInstance();
    final timestamp = prefs.getInt(_agreementDateKey);
    if (timestamp != null) {
      return DateTime.fromMillisecondsSinceEpoch(timestamp);
    }
    return null;
  }

  // 保存同意状态（本地）
  static Future<void> setAgreed(bool agreed) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_agreementKey, agreed);
    
    if (agreed) {
      // 保存版本和时间
      await prefs.setString(_agreementVersionKey, _currentVersion);
      await prefs.setInt(_agreementDateKey, DateTime.now().millisecondsSinceEpoch);
    } else {
      // 清除版本和时间
      await prefs.remove(_agreementVersionKey);
      await prefs.remove(_agreementDateKey);
    }
    
    // 通知 Android 层
    try {
      await _channel.invokeMethod('onAgreementChanged', {'agreed': agreed});
    } catch (e) {
      // 忽略平台通道错误
    }
  }

  // 同步到服务器（登录后调用）
  static Future<void> syncToServer(WidgetRef ref) async {
    try {
      final agreed = await hasAgreed();
      if (agreed) {
        final date = await getAgreementDate();
        final session = ref.read(sessionProvider);
        
        if (session != null) {
          // 调用后端API同步同意状态
          await ref.read(agreementServiceProvider).syncAgreementStatus(
            agreed: true,
            version: _currentVersion,
            agreedAt: date,
          );
        }
      }
    } catch (e) {
      // 同步失败不影响本地状态
      print('同步协议状态失败: $e');
    }
  }

  // 检查服务器状态（可选，用于强制更新）
  static Future<bool> checkServerStatus(WidgetRef ref) async {
    try {
      final session = ref.read(sessionProvider);
      if (session != null) {
        final serverStatus = await ref.read(agreementServiceProvider).getAgreementStatus();
        
        // 如果服务器要求强制更新协议
        if (serverStatus.requiresUpdate) {
          return false; // 需要重新同意
        }
        
        return serverStatus.agreed;
      }
    } catch (e) {
      // 网络错误时使用本地状态
      print('检查服务器协议状态失败: $e');
    }
    
    return await hasAgreed();
  }

  // 清除所有协议相关数据
  static Future<void> clear() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_agreementKey);
    await prefs.remove(_agreementVersionKey);
    await prefs.remove(_agreementDateKey);
  }
}

// 协议服务提供者
final agreementServiceProvider = Provider<AgreementService>((ref) {
  return AgreementService(ref);
});

// 协议服务类
class AgreementService {
  final Ref _ref;
  
  AgreementService(this._ref);

  // 同步协议状态到服务器
  Future<void> syncAgreementStatus({
    required bool agreed,
    required String version,
    DateTime? agreedAt,
  }) async {
    try {
      final session = _ref.read(sessionProvider);
      if (session == null) {
        throw Exception('用户未登录');
      }

      final dio = _ref.read(dioProvider);
      final response = await dio.post(
        '/api/agreement/sync',
        data: {
          'agreed': agreed,
          'version': version,
          'agreedAt': agreedAt?.millisecondsSinceEpoch,
        },
      );

      if (response.statusCode != 200) {
        throw Exception('同步失败: ${response.statusMessage}');
      }

      final data = response.data as Map<String, dynamic>;
      if (data['success'] != true) {
        throw Exception(data['message'] ?? '同步失败');
      }
    } catch (e) {
      print('同步协议状态失败: $e');
      rethrow;
    }
  }

  // 获取服务器协议状态
  Future<AgreementStatus> getAgreementStatus() async {
    try {
      final session = _ref.read(sessionProvider);
      if (session == null) {
        throw Exception('用户未登录');
      }

      final dio = _ref.read(dioProvider);
      final response = await dio.get('/api/agreement/status');

      if (response.statusCode != 200) {
        throw Exception('获取状态失败: ${response.statusMessage}');
      }

      final data = response.data as Map<String, dynamic>;
      if (data['success'] != true) {
        throw Exception(data['message'] ?? '获取状态失败');
      }

      final statusData = data['data'] as Map<String, dynamic>;
      return AgreementStatus(
        agreed: statusData['agreed'] ?? false,
        version: statusData['version'] ?? '1.0.0',
        requiresUpdate: statusData['requiresUpdate'] ?? false,
        agreedAt: statusData['agreedAt'] != null 
            ? DateTime.fromMillisecondsSinceEpoch(statusData['agreedAt'])
            : null,
      );
    } catch (e) {
      print('获取协议状态失败: $e');
      // 返回默认状态
      return AgreementStatus(
        agreed: false,
        version: '1.0.0',
        requiresUpdate: false,
      );
    }
  }
}

// 协议状态数据类
class AgreementStatus {
  final bool agreed;
  final String version;
  final bool requiresUpdate;
  final DateTime? agreedAt;

  AgreementStatus({
    required this.agreed,
    required this.version,
    required this.requiresUpdate,
    this.agreedAt,
  });
}
